package com.imooc.spark.streaming.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * kafka消费者
 */
public class MyKafkaConsumer extends Thread {

    private String topic;

    private KafkaConsumer<String, String> consumer;

    public MyKafkaConsumer(String topic) {
        this.topic = topic;

        Properties props = new Properties();
        props.put("bootstrap.servers", com.imooc.spark.streaming.kafka.MyKafkaProperties.BROKER_LIST);
        props.put("group.id", com.imooc.spark.streaming.kafka.MyKafkaProperties.GROUP_ID);
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        consumer = new KafkaConsumer<String, String>(props);

    }

    @Override
    public void run() {
        consumer.subscribe(Arrays.asList(topic));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(1000);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }
        }
    }
}
